package dcc.component;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class PhotoPanel extends JPanel {

	private BufferedImage image;
	private int width;
	private int height;
	private float c = 3.5f / 2.5f;

	public PhotoPanel() {
		super();
		this.setBackground(Color.white);
	}

	public void loadPhotoFromAppPath(String photoName) {
		File photoFile = new File(System.getProperty("user.dir") + "\\photos\\"
				+ photoName);
		if (photoFile.exists()) {
			this.setPhotoFile(photoFile);
		}
	}

	public void setPhotoFile(File photoFile) {
		this.setToolTipText(photoFile.getName());
		try {
			image = ImageIO.read(photoFile);
			height = this.getHeight();
			width = (int) (height / c);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String savePhotoFileToAppPath(String photoName) {
		String ZPName = "";
		try {
			File dir = new File(System.getProperty("user.dir") + "\\photos");
			if (!dir.exists()) {
				dir.mkdir();
			}
			if (image != null) {
				ZPName = photoName + ".jpg";
				File file = new File(dir.getPath() + "\\" + ZPName);
				ImageIO.write(image, "jpg", file);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ZPName;
	}

	private void drawBorder(Graphics g) {
		g.drawRect(0, 0, this.getWidth() - 1, this.getHeight() - 1);
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		drawBorder(g);
		if (image != null) {
			g.drawImage(image, (this.getWidth() - width) / 2, 2, width, height - 4,
					null);
		}
	}

	public void clearImage() {
		if (this.image != null) {
			this.image = null;
			this.repaint();
		}
	}
}
